import "@ethersproject/shims";
import { ethers } from 'ethers';
import moment from 'moment';
import { global } from "@/config/config";
import api from '@/request/api'
import { max } from '@/utils/util'
import { getValue } from "../deviceStorage";

let rpcProvider
let rpcNode = getValue('RPCNode')
if (rpcNode && rpcNode.includes('http')) {
    rpcProvider = new ethers.providers.JsonRpcProvider(rpcNode);
} else {
    rpcProvider = new ethers.providers.JsonRpcProvider(global.RPCNode);
}
const httpsProvider = rpcProvider

//精简的TransferABI
export const getTransferERC20ABI = (to, amount) => {
    const ABI = ["function transfer(address to, uint256 amount)"];
    const masterIface = new ethers.utils.Interface(ABI);
    const masterAbi = masterIface.encodeFunctionData("transfer", [to, amount]);
    return masterAbi;
}

export const estimateGasForTransferERC20 = async (fromAddress, toAddress, amount) => {
    const data = getTransferERC20ABI(toAddress, amount);
    const estimateGas = await httpsProvider.estimateGas({
        from: fromAddress,
        to: global.ERC20ContractAddress,
        data: data
    })
    let gaslimit = parseInt(estimateGas.toHexString())
    return { gaslimit, data };
}
// 0x1Ad5E9c7B140dc9667E0c9d0538bA37e5cd1ab24  st_usd(USDT) balance
// curl -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0xa48d642F12dF228d7D3A24E3A81EF9e62FbBB548","data":"0x70a082310000000000000000000000001Ad5E9c7B140dc9667E0c9d0538bA37e5cd1ab24"},"latest"],"id":1}' http://192.168.36.150:9545
export const getERC20Balance = async (owner) => {
    const masterABI = ["function balanceOf(address account)"]
    const masterIface = new ethers.utils.Interface(masterABI);
    const masterAbi = masterIface.encodeFunctionData("balanceOf", [owner]);
    const message = await httpsProvider.call({
        to: global.ERC20ContractAddress,
        data: masterAbi
    })
    let decimal = await getERC20Decimal()
    let etherString = ethers.utils.formatUnits(message, decimal);
    return etherString;
}

//查询decimal
export const getERC20Decimal = async () => {
    const masterABI = ["function decimals()"]
    const masterIface = new ethers.utils.Interface(masterABI);
    const masterAbi = masterIface.encodeFunctionData("decimals");
    const message = await httpsProvider.call({
        to: global.ERC20ContractAddress,
        data: masterAbi
    })
    return parseInt(message)
}

export const getERC20GasData = async (rpcurl, fromAddress, toAddress, amount) => {
    //获取矿工费
    let nonce, maxpriorityfee, maxpriorityfeestatic, blocknumber, base_fee
    await api.eth_getTransactionCount(rpcurl, fromAddress).then(res => {
        nonce = parseInt(res.result)
    })
    await api.get_maxPriorityFeePerGas(rpcurl).then(res => {
        let re = parseInt(res.result) / Math.pow(10, 9)
        maxpriorityfee = re
        maxpriorityfeestatic = re
    })
    await api.get_blockinfo(rpcurl).then(res => {
        blocknumber = res.result
    })
    await api.get_newblockinfo(rpcurl, blocknumber).then(res => {
        base_fee = parseInt(res.result.baseFeePerGas) / 1000000000
        base_fee = new Number(base_fee)
    })
    let maxfee = (maxpriorityfee * Math.pow(10, 9) + base_fee * Math.pow(10, 9)) / Math.pow(10, 9)
    let maxfeestatic = (maxpriorityfee * Math.pow(10, 9) + base_fee * Math.pow(10, 9)) / Math.pow(10, 9)
    let gasprice = max(maxfee, maxpriorityfee)
    let money = "0x" + (parseFloat(amount) * Math.pow(10, 6)).toString(16)
    let { data, gaslimit } = await estimateGasForTransferERC20(fromAddress, toAddress, money)
    gaslimit = parseInt(gaslimit * 1.1)
    let gas = gaslimit * gasprice
    gas = gas / Math.pow(10, 9)
    let obj = {
        nonce,
        maxpriorityfee,
        maxpriorityfeestatic,
        blocknumber,
        base_fee,
        maxfee,
        maxfeestatic,
        gasprice,
        gaslimit,
        gas,
        inputdata: data
    }
    return obj
}

export const getERC20TxData = (gasData) => {
    let tx = {
        type: 2,
        nonce: gasData.nonce,
        to: global.ERC20ContractAddress,
        maxPriorityFeePerGas: "0x" + (gasData.maxpriorityfee * Math.pow(10, 9)).toFixed().toString(16),
        maxFeePerGas: "0x" + (gasData.maxfee * Math.pow(10, 9)).toFixed().toString(16),
        gasLimit: "0x" + gasData.gaslimit.toString(16),
        value: "0x0",
        data: gasData.inputdata,
        chainId: 5
    }
    return tx
}

export const getERC20TransferHistory = async (payload) => {
    let url = global.BaseURL + "waddr_token/"
    let startTime = moment(payload.create_time).format("X")
    let endTime = moment().format("X")
    let result = await api.get_transferHistory(url, payload.address, startTime, endTime, 20)
    let sendCount = 0
    let receiveCount = 0
    result && result.forEach(item => {
        if (item.from_address.toLowerCase() === payload.address.toLowerCase()) {
            item.type = 'send'
            sendCount++
        } else {
            item.type = 'receive'
            receiveCount++
        }
        item.valueLabel = item.value + ' ' + item.symbol
    })
    let obj = {
        list: result,
        showReceive: receiveCount > 0 ? true : false,
        showSend: sendCount > 0 ? true : false
    }
    return obj
}
